import { menuStore } from "@/stores/menu";
import { userStore } from "@/stores/user";
import router from "./router";
const whiteList = ["/login"]; // 修正拼写错误
router.beforeEach(async (to, from, next) => {
  const userstore = userStore();
  const menustore = menuStore();
  // 获取 token 和权限列表
  const token = userstore.getToken; // 如果是 getter，请使用括号
  console.log("token", token);
  // 如果是 getter，请使用括号

  if (token) {
    if (to.path === "/login" || to.path === "/") {
      next({ path: "/" });
    } else {
      // 动态添加路由
      // 判断是否已经添加路由
      const hasRoutes = userstore.getCodeList.length > 0;
      if (hasRoutes) {
        next();
      } else {
        try {
          await userstore.getInfo();
          await menustore.getMenuList(router, userstore.getUserId);
          next({ ...to, replace: true });
        } catch (error) {
          console.log("进入catch");
          localStorage.removeItem("userId");
          next({ path: "/login" });
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next({ path: "/login" });
    }
  }
});
